//
//  NetworkTools.swift
//  封装AFN(sft)
//
//  Created by teacher on 16/4/17.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit
import AFNetworking

// 请求方式
enum HMRequestMethod: String {
    case Post = "post"
    case Get = "get"
}

class HMNetworkTools: AFHTTPSessionManager {
    
    // 单例：全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 定义请求
    typealias HMRequestCallBack = (responseObject: AnyObject?, error: NSError?)->()
    
    /// 上传文件
    ///
    /// - parameter method:     请求方式，默认POST
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter datas:      要上传的二进制数据
    /// - parameter finished:   请求完成的回调闭包
    
    
    func upload(urlString:String,pamaters:AnyObject?,datas:[String:NSData],finished:HMRequestCallBack){
        
        self.POST(urlString, parameters: pamaters, constructingBodyWithBlock: { (formData) -> Void in
            //拼接要上传的数据
            for(key,value) in datas {
                
                formData.appendPartWithFileData(value, name: key, fileName: "aa.png", mimeType: "application/octet-stream")
            }
      
            }, progress: nil, success: { (_, response) -> Void in
               //请求成功回调
                finished(responseObject: response, error: nil)
                
                
            }) { (_, error) -> Void in
                //请求失败回调
                finished(responseObject: nil, error: error)
        }
        
    }
    
    // 如果以后在公司开发过程中，某种类型的请求方式使用的频率比较高，那么可以给请求参数添加一个默认值
    /// 发送请求数据
    ///
    /// - parameter method:     请求方式
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter finished:   请求完成之后的回调
    func request(method: HMRequestMethod = .Post, urlString: String, parameters: AnyObject?, finished: HMRequestCallBack){
        
        // 定义一个请求成功之后要执行的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            // 请求成功的回调
            finished(responseObject: responseObject, error: nil)
        }
        
        // 定义一个请求失败之后要执行的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(responseObject: nil, error: error)
        }
        
        if method == .Get {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
